package com.ybbase.framework.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ybbase.framework.base.controller.BaseController;
import com.ybbase.framework.base.model.ResponseBean;
import com.ybbase.framework.common.constant.CommonResultCode;
import com.ybbase.framework.common.util.DateUtil;
import com.ybbase.framework.common.util.EncryptUtil;
import com.ybbase.framework.common.util.MachineUtil;
import com.ybbase.framework.model.po.system.ActiveCode;
import com.ybbase.framework.model.po.system.Log;
import com.ybbase.framework.service.system.ActiveCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 系统过期激活 前端控制器
 *
 * @author cg
 * @since 2019-11-25
 * 云平台2.0
 */
@RestController
@RequestMapping(value = "/active", produces = {"application/json;charset=UTF-8"})
@Api("系统过期激活")
public class ActiveCodeController extends BaseController {

    private static final Logger LOGGER = LogManager.getLogger(ActiveCodeController.class);

    @Value("${mossCode}")
    private String mossCode;

    @Autowired
    private ActiveCodeService activeCodeService;


    /**
     * 激活码获取全部数据
     *
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/all")
    @ApiOperation(value = "激活码获取全部数据", notes = "激活码获取全部数据")
    public ResponseBean findAll() {
        try {
            List<ActiveCode> list = activeCodeService.list();
            String startTime = "";
            String endTime = "";
            String id = "";
            String activeCode = "";
            for (ActiveCode code : list) {
                startTime = DateUtil.getDateTime(code.getStartdate());
                endTime = DateUtil.getDateTime(code.getEnddate());
                id = String.valueOf(code.getId());
                activeCode = code.getEncryption();
            }
            Map<String, String> map = new HashMap<>();
            map.put("id", id);
            map.put("encryption", activeCode);
            map.put("startdate", startTime);
            map.put("enddate", endTime);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "激活码获取全部数据" + CommonResultCode.SUCCESS.getMsg(), map);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("激活码获取全部数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "激活码获取全部数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    @GetMapping("/verificationCode")
    @ApiOperation(value = "验证激活码", notes = "验证激活码")
    public ResponseBean verificationCode(String activeCode) {
        try {
            EncryptUtil encryptUtil = EncryptUtil.getInstance();
            String codes = encryptUtil.aseDecode(activeCode, mossCode);
            String[] codesCg = codes.split("[|]");
            String ipAddress = MachineUtil.getLocalIP();
            String macAddress = MachineUtil.getMacId();
            if (!ipAddress.equals(codesCg[0]) || !macAddress.equals(codesCg[1])) {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "安装激活码的机器有变化请查证后重新输入！", null);
            }
            if (DateUtil.parseDateTime(codesCg[3]).before(new Date())) {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "激活码已过期，请联系管理员！", null);
            }
            //查出原有的数据
            List<ActiveCode> list = activeCodeService.list();

            String now = DateUtil.getDateTime(new Date());
            String endTime = "";
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String id = "";
            for (ActiveCode activeCode1 : list) {
                endTime = DateUtil.getDateTime(activeCode1.getEnddate());
                id = String.valueOf(activeCode1.getId());
            }
            Date sd1 = df.parse(now);
            Date sd2 = df.parse(endTime);

            boolean b = DateUtil.timeVerify(sd1, sd2);
            //如果新时间大于查出数据的日期就更新数据
            if (b == true) {
                ActiveCode code = new ActiveCode();
                code.setId(Integer.valueOf(id));
                code.setIpAddress(ipAddress);
                code.setMacAddress(macAddress);
                code.setEncryption(activeCode);
                code.setStartdate(new Date());
                code.setEnddate(sd2);
                activeCodeService.updateById(code);
            }
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "验证激活码" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("验证激活码异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "验证激活码" + CommonResultCode.FAIL.getMsg());
        }
    }
}